﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using FranceTriple.Dal;

namespace TeamFranceTriple
{
    public partial class ForumList : BaseUserControl
    {
        private String FirstPositionLocalized = "FirstPosition".ToLocalizedString();

        protected void Page_Load(object sender, EventArgs e)
        {
            MarkAllMessageAsReadHyperLink.Visible = ThisMaster.Requester.IsAuthenticated;
            //Fro : Forum et Categorie ne sont pas gérés par les modérateurs.
            ForumCreatePanel1.Visible = ThisMaster.Requester.Roles.Contains("RoleAdminForum");
            CategoryCreatePanel1.Visible = ThisMaster.Requester.Roles.Contains("RoleAdminForum");

            // Les utilisateurs anonymes n'ont pas accès à la fonctionnalité message non-lu, ni à la création de sujet
            if (Session["AnonymousID"] == null)
            {
                NewTopicHyperLink.Visible = true;
                NewTopicHyperLink.NavigateUrl = String.Format("~/{0}/topicdetail/0/0",ThisMaster.Requester.Culture);
                NewTopicHyperLink2.Visible = true;
                NewTopicHyperLink2.NavigateUrl = String.Format("~/{0}/topicdetail/0/0", ThisMaster.Requester.Culture);
                UnreadHyperLink.Visible = true;
                UnreadHyperLink2.Visible = true;
            }
            else
            {
                NewTopicHyperLink.Visible = false;
                NewTopicHyperLink2.Visible = false;
                UnreadHyperLink.Visible = false;
                UnreadHyperLink2.Visible = false;
            }

            HyperLink1.NavigateUrl = String.Format("~/{0}/search", ThisMaster.Requester.Culture);
            HyperLink2.NavigateUrl = String.Format("~/{0}/topic/lasttopic", ThisMaster.Requester.Culture);

            HyperLink3.NavigateUrl = String.Format("~/{0}/topic/lastpost", ThisMaster.Requester.Culture);
            HyperLink4.NavigateUrl = String.Format("~/{0}/topic/lasttopic", ThisMaster.Requester.Culture);
            HyperLink5.NavigateUrl = String.Format("~/{0}/topic/orphan", ThisMaster.Requester.Culture);
            HyperLink6.NavigateUrl = String.Format("~/{0}/search", ThisMaster.Requester.Culture);
            HyperLink7.NavigateUrl =  String.Format("~/{0}/topic/lastpost",ThisMaster.Requester.Culture);
            HyperLink10.NavigateUrl = String.Format("~/{0}/topic/orphan", ThisMaster.Requester.Culture);

            UnreadHyperLink.NavigateUrl = String.Format("~/{0}/topic/unread", ThisMaster.Requester.Culture);
            UnreadHyperLink2.NavigateUrl = String.Format("~/{0}/topic/unread", ThisMaster.Requester.Culture);
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            DataSet ds = new DataSet();
            System.IO.StringReader xmlSR = new System.IO.StringReader(
                ForumCategoryView.GetXmlEntities(((Session["AnonymousID"] == null) ? String.Empty : Session["AnonymousID"].ToString()), ThisMaster.Requester.Profile.TimeZone));
            ds.ReadXml(xmlSR);
            ForumRepeater.DataSource = ds.Tables["Forum"];
            ForumRepeater.DataBind();
        }

        protected void ForumRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            RepeaterItem item = e.Item;
            ICustomTypeDescriptor descriptor;
            DataView view = null;
            DataRowView ThisForum = null;
            String ThisForumId = String.Empty;

            Button btn, btn2;
            Repeater CategoryRepeater;
            DataRowView drv;

            if ((item.ItemType == ListItemType.Item) || (item.ItemType == ListItemType.AlternatingItem))
            {
                // Récupérer les valeurs du forum courant
                descriptor = e.Item.DataItem as ICustomTypeDescriptor;
                if (descriptor != null)
                {
                    var prop = descriptor.GetProperties()[0];
                    ThisForum = (DataRowView)descriptor.GetPropertyOwner(prop);
                    if (ThisForum != null)
                        ThisForumId = ThisForum.Row.ItemArray[1].ToString();
                }

                btn = e.Item.FindControl("EditForumButton") as Button;
                btn2 = e.Item.FindControl("DeleteForumButton") as Button;

                if (ThisMaster.Requester.Roles.Contains("RoleAdminForum"))
                {
                    if (btn != null && btn.CommandName == String.Empty)
                    {
                        btn.Visible = true;
                        btn.CommandName = "EditCommand";
                        if (ThisForum != null)
                            btn.CommandArgument = ThisForumId;
                    }

                    if (btn2 != null && btn2.CommandName == String.Empty)
                    {
                        btn2.Visible = true;
                        btn2.CommandName = "Delete";
                        if (ThisForum != null)
                            btn2.CommandArgument = ThisForumId;
                    }
                }


                CategoryRepeater = (Repeater)item.FindControl("CategoryRepeater");
                drv = (DataRowView)item.DataItem;

                if (drv.DataView.Table.ChildRelations.Count > 0)
                    view = drv.CreateChildView("Forum_ForumCategory");

                if (view != null)
                {
                    CategoryRepeater.DataSource = view;
                    CategoryRepeater.DataBind();
                }
            }
        }

        protected void ForumRepeater_ItemCommand(object sender, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "EditCommand")
            {
                var ForumId = Int32.Parse(e.CommandArgument.ToString());
                var ForumEditing = ForumDal.GetEntity(ForumId);

                ForumIdLabel.Value = ForumId.ToString();
                LabelForumTextBox.Text = ForumEditing.LabelForum;
                InsertAfterForumDropDownList.SelectedValue = (ForumEditing.OrderForum == 0) ?
                    ForumEditing.OrderForum.ToString() :
                    (ForumEditing.OrderForum - 10).ToString();

                foreach (var listViewDataItem in RolesForumListView.Items)
                {
                    var RoleIdLabel = (Label)listViewDataItem.FindControl("RoleIdLabel");
                    var RightLevelDropDownList = (DropDownList)listViewDataItem.FindControl("RightLevelDropDownList");

                    if (RightLevelDropDownList != null && RoleIdLabel != null)
                    {
                        var Role_Id = Guid.Parse(RoleIdLabel.Text.ToString());
                        RightLevelDropDownList.SelectedValue = UserAccessDal.ForumRightLevel(ForumId, Role_Id).ToString();
                    }
                }
            }

            if (e.CommandName == "Delete")
            {
                ForumDal.DeleteEntity(Int32.Parse(e.CommandArgument.ToString()));
            }
        }

        protected void CategoryRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            RepeaterItem item = e.Item;
            ICustomTypeDescriptor descriptor;
            HyperLink forumTopicHyperLink = (HyperLink)((RepeaterItem)e.Item).FindControl("ForumTopicHyperLink");

            DataRowView ThisCategory = null;
            String ThisCategoryId = String.Empty;
            Button btn, btn2;
            HyperLink lastPostHyperLink;

            if ((item.ItemType == ListItemType.Item) || (item.ItemType == ListItemType.AlternatingItem))
            {
                // Récupérer les valeurs du Category courant
                descriptor = item.DataItem as ICustomTypeDescriptor;
                if (descriptor != null)
                {
                    var prop = descriptor.GetProperties()[0];
                    ThisCategory = (DataRowView)descriptor.GetPropertyOwner(prop);
                    if (ThisCategory != null)
                        ThisCategoryId = ThisCategory.Row.ItemArray[0].ToString();
                }

                btn = item.FindControl("EditCategoryButton") as Button;
                btn2 = item.FindControl("DeleteCategoryButton") as Button;

                if (ThisMaster.Requester.Roles.Contains("RoleAdminForum"))
                {
                    if (btn != null && btn.CommandName == String.Empty)
                    {
                        btn.Visible = true;
                        btn.CommandName = "EditCommand";
                        if (ThisCategory != null)
                            btn.CommandArgument = ThisCategoryId;
                    }

                    if (btn2 != null && btn2.CommandName == String.Empty)
                    {
                        btn2.Visible = true;
                        btn2.CommandName = "Delete";
                        if (ThisCategory != null)
                            btn2.CommandArgument = ThisCategoryId;
                    }
                }

                //Todo: la position 1 dans le tableau peut changée en fonction des résultats de la requete
                // par exemple quand il n'existe ni sujet de discussion ni message.
                if (forumTopicHyperLink != null)
                    forumTopicHyperLink.NavigateUrl = String.Format("~/{0}/topic/bycategory/{1}", ThisMaster.Requester.Culture, ((DataRowView)e.Item.DataItem).Row.ItemArray[0].ToString());

                lastPostHyperLink = (HyperLink)((RepeaterItem)e.Item).FindControl("LastPostHyperLink");

                if (lastPostHyperLink != null)
                    lastPostHyperLink.NavigateUrl = String.Format("~/{0}/forumpost/showpost/{1}", ThisMaster.Requester.Culture, ((DataRowView)e.Item.DataItem).Row.ItemArray[6].ToString());
            }
        }

        protected void CategoryRepeater_ItemCommand(object sender, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "EditCommand")
            {
                var CategoryId = Int32.Parse(e.CommandArgument.ToString());
                var CategoryEditing = ForumCategoryDal.GetEntity(CategoryId);

                CategoryIdLabel.Value = CategoryId.ToString();
                LabelCategoryTextBox.Text = CategoryEditing.LabelForumCategory;
                DescriptionTextBox.Text = CategoryEditing.DescriptionForumCategory;
                ForumIdDropDownList.SelectedValue = ForumDal.GetForumIdByCategoryId(CategoryId).ToString();

                ForumCategoryEntityDataSource.WhereParameters["ForumIdParam"].DefaultValue = ForumIdDropDownList.SelectedValue;
                InsertAfterCategoryDropDownList.DataBind();

                InsertAfterCategoryDropDownList.SelectedValue = (CategoryEditing.OrderForumCategory == 0) ?
                    CategoryEditing.OrderForumCategory.ToString() :
                    (CategoryEditing.OrderForumCategory - 10).ToString();

                foreach (var listViewDataItem in RolesForumListView.Items)
                {
                    var RoleIdLabel = (Label)listViewDataItem.FindControl("RoleIdLabel");
                    var RightLevelDropDownList = (DropDownList)listViewDataItem.FindControl("RightLevelDropDownList");

                    if (RightLevelDropDownList != null && RoleIdLabel != null)
                    {
                        var Role_Id = Guid.Parse(RoleIdLabel.Text.ToString());
                        RightLevelDropDownList.SelectedValue = UserAccessDal.ForumRightLevel(CategoryId, Role_Id).ToString();
                    }
                }

            }

            if (e.CommandName == "Delete")
            {
                ForumCategoryDal.DeleteEntity(Int32.Parse(e.CommandArgument.ToString()));
            }
        }

        protected void AddForumPopupButton_Click(object sender, EventArgs e)
        {
            if (!this.Page.IsValid)
                return;
            Int32 id = 0;
            Forum forumToUpdate = null;

            if (LabelForumTextBox.Text != string.Empty)
            {
                List<aspnet_RolesForumSet> roleForums = new List<aspnet_RolesForumSet>();
                foreach (var listViewDataItem in RolesForumListView.Items)
                {
                    var RoleIdLabel = (Label)listViewDataItem.FindControl("RoleIdLabel");
                    var RightLevelDropDownList = (DropDownList)listViewDataItem.FindControl("RightLevelDropDownList");

                    if (RightLevelDropDownList != null && RoleIdLabel != null && RightLevelDropDownList.SelectedIndex > 0)
                    {

                        var AspNetRoleEntity = UserProfile.AspNetRoleGetEntity(Guid.Parse(RoleIdLabel.Text.ToString()));
                        var RightLevel = Int16.Parse(RightLevelDropDownList.SelectedValue.ToString());

                        // Les roles auteur & modérateur sont interdit à Public :
                        if (AspNetRoleEntity.LoweredRoleName == "public" && (RightLevel == 2 || RightLevel == 3))
                            continue;

                        roleForums.Add(new aspnet_RolesForumSet()
                        {
                            Role_Id = Guid.Parse(RoleIdLabel.Text.ToString()),
                            aspnet_Roles = AspNetRoleEntity,
                            RightLevel = RightLevel
                        });
                    }
                }

                id = Int32.Parse(ForumIdLabel.Value);

                if (id == 0)
                    id = ForumDal.CreateEntity(
                        new Forum()
                        {
                            LabelForum = LabelForumTextBox.Text,
                            OrderForum = (Int32.Parse((InsertAfterForumDropDownList.SelectedValue == String.Empty) ? "0" : InsertAfterForumDropDownList.SelectedValue)) + 10
                        }, roleForums);
                else
                {
                    forumToUpdate = ForumDal.GetEntity(id);
                    forumToUpdate.LabelForum = LabelForumTextBox.Text;
                    forumToUpdate.OrderForum = (Int32.Parse((InsertAfterForumDropDownList.SelectedValue == String.Empty) ?
                        "0" : InsertAfterForumDropDownList.SelectedValue)) + 10;
                    ForumDal.UpdateEntity(forumToUpdate, roleForums);
                }

                ForumIdLabel.Value = "0";
                LabelForumTextBox.Text = String.Empty;

                // Est ce que tous les accès reviennent sur aucun ?
                RolesForumListView.DataBind();

                ForumIdDropDownList.DataBind();
                InsertAfterForumDropDownList.DataBind();
            }
        }

        protected void AddCategoryPopupButton_Click(object sender, EventArgs e)
        {
            if (!this.Page.IsValid)
                return;
            Int32 id = Int32.Parse(CategoryIdLabel.Value);
            ForumCategory categoryToUpdate = null;

            if (id == 0)
            {
                id = ForumCategoryDal.CreateEntity(
                    new ForumCategory()
                    {
                        LabelForumCategory = LabelCategoryTextBox.Text,
                        DescriptionForumCategory = DescriptionTextBox.Text,
                        OrderForumCategory = (Int32.Parse((InsertAfterCategoryDropDownList.SelectedValue == String.Empty) ? "0" : InsertAfterCategoryDropDownList.SelectedValue)) + 10,
                        Forum = ForumDal.GetEntity(Int32.Parse(ForumIdDropDownList.SelectedValue)),
                    });
            }
            else
            {
                categoryToUpdate = ForumCategoryDal.GetEntity(id);
                categoryToUpdate.LabelForumCategory = LabelCategoryTextBox.Text;
                categoryToUpdate.DescriptionForumCategory = DescriptionTextBox.Text;
                categoryToUpdate.OrderForumCategory = (Int32.Parse((InsertAfterCategoryDropDownList.SelectedValue == String.Empty) ?
                    "0" : InsertAfterCategoryDropDownList.SelectedValue)) + 10;
                ForumCategoryDal.UpdateEntity(categoryToUpdate, Int32.Parse(ForumIdDropDownList.SelectedValue));
            }

            CategoryIdLabel.Value = "0";
            LabelCategoryTextBox.Text = String.Empty;
            DescriptionTextBox.Text = String.Empty;
            ForumCategoryEntityDataSource.WhereParameters["ForumIdParam"].DefaultValue = ForumIdDropDownList.SelectedValue;
            InsertAfterCategoryDropDownList.DataBind();
        }

        protected void ForumIdDropDownList_SelectedIndexChanged(object sender, EventArgs e)
        {
            //Todo : code a déplacer coté client pour éviter un post back ? 
            ForumCategoryEntityDataSource.WhereParameters["ForumIdParam"].DefaultValue = ForumIdDropDownList.SelectedValue;
        }

        protected void InsertAfterForumDropDownList_OnDataBound(object sender, EventArgs e)
        {
            InsertAfterForumDropDownList.Items.Insert(0, new ListItem() { Text = FirstPositionLocalized, Value = "0" });
        }

        protected void InsertAfterCategoryDropDownList_OnDataBound(object sender, EventArgs e)
        {
            InsertAfterCategoryDropDownList.Items.Insert(0, new ListItem() { Text = FirstPositionLocalized, Value = "0" });
        }

        protected void MarkAllMessageAsReadHyperLink_Click(object sender, EventArgs e)
        {
            if (!ThisMaster.Requester.IsAuthenticated)
                return;

            Int32 TotalMarkedMessage = ForumPostDal.MarkAllAsRead(Guid.Parse(ThisMaster.Requester.Membership.ProviderUserKey.ToString()));
        }

        protected void RolesForumListView_ItemDatabound(object sender, ListViewItemEventArgs e)
        {
            ListViewItem item = e.Item;
            aspnet_Role ThisRole = null;
            Label RoleNameLabel;

            if (item.ItemType == ListViewItemType.DataItem)
            {
                ThisRole = item.DataItem as aspnet_Role;
                if (ThisRole != null)
                {

                    RoleNameLabel = item.FindControl("RoleNameLabel") as Label;
                    if (RoleNameLabel != null)
                    {
                        RoleNameLabel.Text = ThisRole.RoleName.ToLocalizedString();
                    }

                    // Le role public n'a pas le droit d'être auteur ou modérateur
                    if (ThisRole.LoweredRoleName == "public")
                    {
                        var rightsList = e.Item.FindControl("RightLevelDropDownList") as DropDownList;
                        if (rightsList != null)
                        {
                            rightsList.Items.RemoveAt(3);
                            rightsList.Items.RemoveAt(2);
                        }
                    }
                }
            }
        }
    }
}
